import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { uniqueId } from 'lodash';
import { DatatableComponent } from '@iux/live';

interface DemoUser {
  id: string;
  name: string;
  age: number;
  expand: boolean;
  random: number;
  disabled: boolean;
}

@Component({
  selector: 'app-row-selection-max',
  templateUrl: './row-selection-max.component.html',
  styles: [
    `
      lv-paginator {
        margin-top: 16px;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RowSelectionMaxComponent implements OnInit {
  data: DemoUser[];
  selection: DemoUser[];
  private _selectionMax = 3;
  private _isSelectionMax = false;
  private _disabledData = new Set();

  @ViewChild(DatatableComponent, { static: false }) lvTable: DatatableComponent;
  constructor() {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.data = Array.from({ length: 10 }).map((_, key) => this.initUser(key, key % 2 !== 0));
    // 直接赋值选中项
    this.selection = [this.data[0], this.data[2]];
  }

  initUser(key: number, disabled: boolean) {
    return {
      id: uniqueId('uid'),
      name: `user${key}`,
      age: 10 + key,
      expand: false,
      random: parseInt(`${Math.random() * 100}`, 10),
      disabled,
      checkboxTip: disabled ? '当前数据不可选择' : '',
    };
  }

  selectionChange() {
    const { length } = this.selection;
    if (length >= this._selectionMax) {
      this.data.forEach(item => {
        if (!this.selection.includes(item) && !item.disabled) {
          this._disabledData.add(this.lvTable.result(item));
        }
      });
      this.setDisabledStatus(true);
    } else {
      this._isSelectionMax && this.setDisabledStatus(false);
    }
  }

  setDisabledStatus(disabled: boolean) {
    this.data.forEach(item => {
      if (this._disabledData.has(this.lvTable.result(item))) {
        item.disabled = disabled;
      }
    });
    !disabled && this._disabledData.clear();
    this._isSelectionMax = disabled;
  }
}
